package server;

import common.Contact;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DataAccess {
    private static final String CONTACTS_FILE = "src/main/resources/contacts.txt";

    public List<Contact> readContacts() throws IOException {
        List<Contact> contacts = new ArrayList<>();
        File file = new File(CONTACTS_FILE);
        if (!file.exists()) {
            return contacts;
        }

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] parts = line.split(":");
            contacts.add(new Contact(parts[0], parts[1]));
        }
        reader.close();
        return contacts;
    }

    public void writeContacts(List<Contact> contacts) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(CONTACTS_FILE));
        for (Contact contact : contacts) {
            writer.write(contact.toString());
            writer.newLine();
        }
        writer.close();
    }
}
